<template>
  <div class="space-y-6">
    <!-- 页面标题和操作 -->
    <div class="flex justify-between items-center">
      <h2 class="text-2xl font-bold text-gray-900">畅销管理</h2>
      <el-button type="primary" @click="updateBestsellerRankings" :loading="updating">
        <i class="fas fa-sync-alt mr-2"></i>
        {{ updating ? '更新中...' : '更新榜单' }}
      </el-button>
    </div>

    <!-- 搜索和筛选 -->
    <div class="bg-white rounded-lg shadow-sm p-6 border border-gray-200">
      <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
        <el-input
          v-model="searchForm.title"
          placeholder="图书标题"
          clearable
        >
          <template #prefix>
            <i class="fas fa-book text-gray-400"></i>
          </template>
        </el-input>
        <el-select v-model="searchForm.categoryId" placeholder="分类" clearable>
          <el-option label="全部分类" value=""></el-option>
          <el-option label="综合榜" value="0"></el-option>
          <el-option
            v-for="category in categories"
            :key="category.id"
            :label="category.name"
            :value="category.id"
            v-if="category && category.id !== 1"
          ></el-option>
        </el-select>
        <el-select v-model="searchForm.period" placeholder="周期" clearable>
          <el-option label="全部周期" value=""></el-option>
          <el-option label="日榜" value="daily"></el-option>
          <el-option label="周榜" value="weekly"></el-option>
          <el-option label="月榜" value="monthly"></el-option>
        </el-select>
        <div class="flex space-x-2">
          <el-button type="primary" @click="handleSearch">
            <i class="fas fa-search mr-2"></i>
            搜索
          </el-button>
          <el-button @click="resetSearch">重置</el-button>
        </div>
      </div>
    </div>

    <!-- 畅销榜单列表 -->
    <div class="bg-white rounded-lg shadow-sm border border-gray-200">
      <el-table
        :data="bestsellerList"
        v-loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="rank" label="排名" width="80" />
        <el-table-column label="封面" width="100">
          <template #default="{ row }">
            <img
              :src="getImageUrl(row.book?.cover)"
              :alt="row.book?.title"
              class="book-cover-thumbnail"
              @error="handleImageError"
            >
          </template>
        </el-table-column>
        <el-table-column label="图书信息" min-width="210" align="center">
          <template #default="{ row }">
            <div>
              <div class="font-medium">书名：{{ row.book?.title }}</div>
              <div class="text-sm text-gray-500">作者：{{ row.book?.author }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="分类" width="120">
          <template #default="{ row }">
            <el-tag v-if="(row.category_id || row.categoryId) === -1" type="warning">综合榜</el-tag>
            <el-tag v-else>{{ getCategoryName(row.category_id || row.categoryId) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="周期" width="100">
          <template #default="{ row }">
            <el-tag 
              :type="getPeriodTagType(row.period)"
              size="small"
            >
              {{ getPeriodName(row.period) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="价格" width="100">
          <template #default="{ row }">
            <span class="text-red-600 font-medium">¥{{ row.book?.price }}</span>
          </template>
        </el-table-column>
        <el-table-column label="销量" width="80">
          <template #default="{ row }">
            {{ row.book?.sales || 0 }}
          </template>
        </el-table-column>
        <el-table-column label="更新时间" width="150">
          <template #default="{ row }">
            {{ formatDate(row.updated_at || row.updatedAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right" align="center" >
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="viewBookDetail(row)">
              <i class="fas fa-eye mr-1"></i>
              查看详细
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="flex justify-center py-4">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 图书详情弹窗 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="图书详情"
      width="800px"
      :before-close="handleCloseDetail"
    >
      <div v-if="currentBook" class="space-y-6">
        <!-- 基本信息 -->
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <!-- 图书封面 -->
          <div class="flex justify-center">
            <div class="w-48 h-64 bg-gray-100 rounded-lg overflow-hidden shadow-sm">
              <img
                :src="getBookCover(currentBook.cover)"
                :alt="currentBook.title"
                class="w-full h-full object-cover"
                @error="handleImageError"
              />
            </div>
          </div>

          <!-- 图书信息 -->
          <div class="space-y-4">
            <div class="grid grid-cols-2 gap-4">
              <div>
                <label class="text-sm font-medium text-gray-700 font-semibold">图书标题</label>
                <p class="mt-1 text-gray-900">{{ currentBook.title }}</p>
              </div>
              <div>
                <label class="text-sm font-medium text-gray-700 font-semibold">作者</label>
                <p class="mt-1 text-gray-900">{{ currentBook.author }}</p>
             </div>
            </div>
            <div class="grid grid-cols-2 gap-4">
              <div>
                <label class="text-sm font-medium text-gray-700 font-semibold">出版社</label>
                <p class="mt-1 text-gray-900">{{ currentBook.publisher }}</p>
              </div>
              <div>
                <label class="text-sm font-medium text-gray-700 font-semibold">分类</label>
                <p class="mt-1 text-gray-900">{{ getCategoryName(currentBook.categoryId) }}</p>
              </div>
            </div>

            <div class="grid grid-cols-2 gap-4">
              <div>
                <label class="text-sm font-medium text-gray-700 font-semibold">价格</label>
                <p class="mt-1 text-xl font-bold text-red-600">¥{{ currentBook.price }}</p>
              </div>
              <div>
                <label class="text-sm font-medium text-gray-700 font-semibold">销量</label>
                <p class="mt-1 text-lg font-semibold text-green-600">{{ currentBook.sales || 0 }}</p>
              </div>
            </div>

            <div class="grid grid-cols-2 gap-4">
              <div>
                <label class="text-sm font-medium text-gray-700 font-semibold">库存</label>
                <p class="mt-1 text-gray-900">{{ currentBook.stock || 0 }}</p>
              </div>
              <div>
                <label class="text-sm font-medium text-gray-700 font-semibold">评分</label>
                <p class="mt-1 text-gray-900">{{ currentBook.rating || '暂无评分' }}</p>
              </div>
            </div>
          </div>
        </div>

        <!-- 图书描述 -->
        <div v-if="currentBook.description">
          <label class="text-sm font-medium text-gray-700 font-semibold">图书简介</label>
          <p class="mt-2 text-gray-900 leading-relaxed">{{ currentBook.description }}</p>
        </div>

        <!-- 榜单信息 -->
        <div class="bg-gray-50 rounded-lg p-4">
          <h4 class="text-lg font-semibold text-gray-900 mb-3">榜单信息</h4>
          <div class="grid grid-cols-3 gap-4">
            <div>
              <label class="text-sm font-medium text-gray-700 font-semibold">排名</label>
              <p class="mt-1 text-2xl font-bold text-blue-600">#{{ currentRank }}</p>
            </div>
            <div>
              <label class="text-sm font-medium text-gray-700 font-semibold">分类</label>
              <p class="mt-1 text-gray-900">{{ getCategoryName(currentCategoryId) }}</p>
            </div>
            <div>
              <label class="text-sm font-medium text-gray-700 font-semibold">周期</label>
              <p class="mt-1 text-gray-900">{{ getPeriodName(currentPeriod) }}</p>
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="flex justify-end">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { adminAPI } from '@/api/admin.js'
import { merchantAPI } from '@/api/merchant.js'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()
const loading = ref(false)
const updating = ref(false)

// 根据用户角色选择API
const currentAPI = computed(() => {
  return userStore.isMerchant ? merchantAPI : adminAPI
})

const searchForm = reactive({
  title: '',
  categoryId: '',
  period: ''
})



const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const bestsellerList = ref([])
const categories = ref([])

// 详情弹窗相关
const detailDialogVisible = ref(false)
const currentBook = ref(null)
const currentRank = ref(0)
const currentCategoryId = ref(0)
const currentPeriod = ref('')



// 加载畅销榜单列表
const loadBestsellerList = async () => {
  loading.value = true
  try {
    const params = {
      current: pagination.currentPage,
      size: pagination.pageSize,
      ...searchForm
    }

    const response = await currentAPI.value.getBestsellerList(params)

    if (response.records) {
      bestsellerList.value = response.records || []
      pagination.total = response.total || 0
    } else if (response.data && response.data.records) {
      bestsellerList.value = response.data.records || []
      pagination.total = response.data.total || 0
    } else {
      console.error('数据格式错误:', response)
      ElMessage.error('数据格式错误')
    }
  } catch (error) {
    console.error('加载畅销榜单失败:', error)
    console.error('错误详情:', error.response)
    ElMessage.error('加载畅销榜单失败: ' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

// 加载分类列表
const loadCategories = async () => {
  try {
    const response = await currentAPI.value.getCategoryList({})

    let categoryData = []
    if (response.records) {
      categoryData = response.records || []
    } else if (response.data && response.data.records) {
      categoryData = response.data.records || []
    }

    categories.value = categoryData
  } catch (error) {
    console.error('加载分类失败:', error)
    ElMessage.error('加载分类失败')
  }
}



// 搜索处理
const handleSearch = () => {
  pagination.currentPage = 1
  loadBestsellerList()
}

const resetSearch = () => {
  Object.assign(searchForm, {
    title: '',
    categoryId: '',
    period: ''
  })
  handleSearch()
}







// 更新畅销榜单
const updateBestsellerRankings = async () => {
  updating.value = true
  try {
    const response = await currentAPI.value.generateBestsellerRankings()
    if (response.code === 200) {
      ElMessage.success('畅销榜单更新成功')
      loadBestsellerList() // 重新加载列表
    } else {
      ElMessage.error(response.message || '更新失败')
    }
  } catch (error) {
    console.error('更新畅销榜单失败:', error)
    ElMessage.error('更新失败：' + (error.response?.data?.message || error.message))
  } finally {
    updating.value = false
  }
}

const viewBookDetail = (row) => {
  if (row.book && row.book.id) {
    currentBook.value = row.book
    currentRank.value = row.rank
    currentCategoryId.value = row.categoryId
    currentPeriod.value = row.period
    detailDialogVisible.value = true
  } else {
    ElMessage.warning('图书信息不完整')
  }
}

const handleCloseDetail = () => {
  detailDialogVisible.value = false
  currentBook.value = null
  currentRank.value = 0
  currentCategoryId.value = 0
  currentPeriod.value = ''
}

const getBookCover = (cover) => {
  if (!cover) return ''
  if (cover.startsWith('http')) return cover
  if (cover.startsWith('/uploads/')) return `http://localhost:8081/api${cover}`
  return ''
}



// 分页处理
const handleSizeChange = (size) => {
  pagination.pageSize = size
  loadBestsellerList()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadBestsellerList()
}

// 工具方法
const getCategoryName = (categoryId) => {
  // 如果categoryId是undefined或null，返回未知分类
  if (categoryId === undefined || categoryId === null) {
    return '未知分类'
  }

  // 转换为数字类型进行比较
  const numCategoryId = Number(categoryId)

  if (numCategoryId === 0) {
    return '综合榜'
  }

  const category = categories.value.find(cat => Number(cat.id) === numCategoryId)
  return category ? category.name : '未知分类'
}

const getPeriodName = (period) => {
  const periodMap = {
    daily: '日榜',
    weekly: '周榜',
    monthly: '月榜'
  }
  return periodMap[period] || period
}

const getPeriodTagType = (period) => {
  const typeMap = {
    daily: 'success',
    weekly: 'warning',
    monthly: 'primary'
  }
  return typeMap[period] || ''
}

const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  if (isNaN(date.getTime())) return '无效日期'
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const getImageUrl = (url) => {
  if (!url) return ''

  // 如果是完整的URL，直接返回
  if (url.startsWith('http')) {
    return url
  }

  // 如果是上传的文件路径
  if (url.startsWith('/uploads/')) {
    return `http://localhost:8081/api${url}`
  }

  // 如果是静态资源路径
  if (url.startsWith('/assets/')) {
    return `http://localhost:8081/api${url}`
  }

  // 其他情况，添加API前缀
  return `/api${url}`
}

// 图片加载错误处理
const handleImageError = (event) => {
  console.error('图片加载失败:', event.target.src)
  // 设置默认图片
  event.target.src = ''
}

onMounted(() => {
  loadBestsellerList()
  loadCategories()
})
</script>

<style scoped>
.book-cover-thumbnail {
  width: 60px;
  height: 80px;
  object-fit: contain;
  border-radius: 4px;
  border: 1px solid #e5e7eb;
  background-color: #f9f9f9;
}
</style>
